//
//  ShikeViewController.m
//  ThePrivateKitchen
//
//  Created by lirui on 16/1/20.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "ShikeViewController.h"
#import "FoodModel.h"
#import "StepTableViewCell.h"
#import "HeadTableViewCell.h"
#import "NewViewController.h"
#import "UMSocial.h"
#import "DataBaseManager.h"

@interface ShikeViewController ()<UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate>
@property(nonatomic, retain)NSMutableArray *dataArr;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)FoodModel *foodModel;
@property (nonatomic, assign) BOOL isT;

//@property(nonatomic,retain) *shareURL;
@end

@implementation ShikeViewController
- (void)dealloc
{
    [_dataArr release];
    [_tableView release];
    [_foodModel release];
    [super dealloc];
}
-(void)viewWillAppear:(BOOL)animated
{

    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //重写左按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"left@3x"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    //开启数据库
    [[DataBaseManager shareInstance]  openDB];
    [[DataBaseManager shareInstance] createTable];
     //分享按钮
    UIButton *share = [ UIButton buttonWithType: UIButtonTypeCustom];
    [share setImage:[UIImage imageNamed:@"分享@2x"]forState:UIControlStateNormal];
    share.frame = CGRectMake(WIDTH *300, 0, 30*WIDTH, 30*HEIGHT);
    [share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *sharebar = [[UIBarButtonItem alloc]initWithCustomView:share];
  
    //收藏按钮
    _isT = NO;
    UIButton *shoucang = [ UIButton buttonWithType:UIButtonTypeCustom];
    [shoucang setImage:[UIImage imageNamed:@"收藏@2x"] forState:UIControlStateNormal];
    [shoucang setImage:[UIImage imageNamed:@"收藏_p@2x"] forState:UIControlStateSelected];
    shoucang.selected = NO;
    shoucang.frame = CGRectMake(WIDTH *300, 0, 30*WIDTH, 30*HEIGHT);
    [shoucang addTarget:self action:@selector(shoucang:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *shoucangbar = [[UIBarButtonItem alloc]initWithCustomView:shoucang];
     self.navigationItem.rightBarButtonItems = @[shoucangbar,sharebar];
    [self dataHandler];
    [self creatView];
    [self loadMBProgress];
    
    
    
}

-(void)leftAction:(UIBarButtonItem *)left
{
    [self.navigationController popViewControllerAnimated:YES];
}
//数据请求
-(void)dataHandler
{
    NSString *str =[NSString stringWithFormat:@"http://api.izhangchu.com/?dishes_id=%@&methodName=DishesView&user_id=0&version=1.0", self.model.dishes_id];
    [LRAFNetwork postUrlString:str body:nil response:JSON bodyStyle:RequestJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        //提取图片的数组
        self.foodModel  = [ FoodModel modelWithDic:responseObject[@"data"]];
        NSLog(@"~~~~%@",_foodModel);
        //提取步骤数组
        self.dataArr =  responseObject[@"data"][@"step"];
    
      
        [_tableView reloadData];
        [self.hud removeFromSuperview];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    
}
-(void)creatView
{
    self.tableView = [[ UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH *375, HEIGHT *667) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    _tableView .dataSource =self;
    _tableView.delegate = self;
//注册第一种cell
    [_tableView registerClass:[StepTableViewCell class] forCellReuseIdentifier:@"stepcell"];
   //注册第二种cell
    [_tableView registerClass:[HeadTableViewCell class] forCellReuseIdentifier:@"headcell"];
    [self.view addSubview:_tableView];
    [_tableView release];
    
}


#pragma mark -分区数 一共有两种cell
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count + 1;
}

#pragma mark - row个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

#pragma mark - row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{//如果是第一个分区 也就是图片的区域
    if (indexPath.section == 0) {
        return HEIGHT *667;
    }else{
        return 260 * HEIGHT ;
    }
}

#pragma mark - 创建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        // 从重用池中获取cell
       HeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"headcell" forIndexPath:indexPath];
        
        // cell赋值
        cell.f_model = self.foodModel;
//播放器block传值
        PLAYBLOCK playerblock = ^(NSString *str)
        {
            NewViewController *newViedo = [[ NewViewController alloc] init];
            newViedo.string = str;
            [self.navigationController pushViewController:newViedo animated:YES];
        };
        //block 实现
        cell.play = playerblock;
        // 取消点击变灰
       [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        // 返回cell
        return cell;
    }else{
        // 从重用池中获取cell
       StepTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"stepcell" forIndexPath:indexPath];
        
        // cell赋值
        cell.num = indexPath.section;
        //把步骤里的每个字典传给cell
        cell.stepDic = self.dataArr[indexPath.section - 1];
        
        // 取消点击变灰
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        // 返回cell
        return cell;
    }
    return nil;
}

#pragma mark - section头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{  
    if (section == 0) {
        return 0.01 * HEIGHT;
    }
    return 20 * HEIGHT;
}
//收藏按钮
-(void)shoucang:(UIButton *)cang
{
    _isT = !_isT;
    /**收藏*/
    if(_isT)
    {
        cang.selected = YES;

    NSMutableArray *shareArr = [[DataBaseManager shareInstance] select];
    for (FoodModel *r in shareArr) {
        if ([r.dashes_name isEqualToString:_foodModel.dashes_name])
        {

            return;
        }
    }
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:a animated:YES completion:^{
        }];
        //延时消失
    [self performSelector:@selector(diss) withObject:self afterDelay:2];
        
        [[DataBaseManager shareInstance] insertfood:self.foodModel];
    }else
    {
        /**取消收藏*/
        cang.selected = NO;

        //提示框
        UIAlertController *c = [UIAlertController alertControllerWithTitle:@"提示" message:@"取消收藏" preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:c animated:YES completion:^{
        }];
        
        [self performSelector:@selector(diss) withObject:self afterDelay:2];

        [[DataBaseManager shareInstance] deletename:self.foodModel.dashes_name];
        
    }
}
-(void)diss
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


-(void)shareAction:(UIBarButtonItem *)s
{
   
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"56a881e5e0f55ad4a0000581" shareText:[NSString stringWithFormat:@"%@ %@",self.foodModel.dashes_name,self.foodModel.share_url] shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren, nil] delegate:self];
     NSLog(@"%@ %@",self.foodModel.dashes_name,self.foodModel.share_url);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
